package megrez.bussiness.system.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;

import org.springframework.beans.BeanUtils;

import lombok.Getter;
import lombok.Setter;
import megrez.common.jpa.AbstractIdAuditingEntity;

/**
 * 部门
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Entity
@Getter
@Setter
@Table(name = "dept")
@NamedEntityGraphs({
        @NamedEntityGraph(name = "Dept.children", attributeNodes = {
                @NamedAttributeNode("children")
        })
})
public class Dept extends AbstractIdAuditingEntity {
    public final static String PATH_SEP = "/";
    /**
     * 上级部门
     */
    @ManyToOne
    @JoinColumn(name = "parentId")
    private Dept parent;

    /**
     * 代码
     */
    @Column(nullable = false, unique = true, updatable = false)
    private String code;

    /**
     * 名称
     */
    @Column(nullable = false)
    private String name;

    /**
     * 启用
     */
    private Boolean enabled;

    /**
     * 排序
     */
    private Integer orderNo;

    /**
     * 代码路径
     */
    private String pathCode;

    /** 是否末级 */
    private Boolean isLeaf;

    /**
     * 子部门
     */
    @OneToMany(mappedBy = "parent", cascade = { CascadeType.PERSIST })
    private List<Dept> children = new ArrayList<>();

    public Dept() {
    }

    public Dept(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public Dept(Dept parent, String code, String name) {
        this.parent = parent;
        this.code = code;
        this.name = name;
    }

    @PrePersist
    @PreUpdate
    public void preAction() {
        if (parent != null) {
            pathCode = parent.getPathCode() + PATH_SEP + code;
        } else {
            pathCode = code;
        }

        if (enabled == null) {
            enabled =  true;
        }
        if (orderNo == null) {
            orderNo = 0;
        }

        if (isLeaf == null) {
            isLeaf = true;
        }
    }

    public void copy(Dept source) {
        BeanUtils.copyProperties(source, this, "id,parent,pathCode,children".split(","));
    }

}
